package com.bjy.qa.service.tools.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjy.qa.dao.tools.OcrDao;
import com.bjy.qa.entity.MyPage;
import com.bjy.qa.entity.ResponsePagingData;
import com.bjy.qa.entity.tools.Ocr;
import com.bjy.qa.enumtype.Status;
import com.bjy.qa.service.tools.IOcrService;
import com.bjy.qa.util.ocr.OcrTools;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class OcrService implements IOcrService {
    @Resource
    OcrDao ocrDao;

    @Override
    public ResponsePagingData list(MyPage<Ocr> myPage) throws Exception {
        Page<Ocr> page = new Page(myPage.getPageNum(), myPage.getPageSize()); // 构造待查询 page 对象
        page.setOrders(myPage.getOrders()); // 设置排序字段

        // 构造待查询 QueryWrapper
        Ocr ocr = myPage.getQuery();
        QueryWrapper<Ocr> queryWrapper = new QueryWrapper<>();
        if (ocr != null) {
            if (StringUtils.isNotBlank(ocr.getFileName())) {
                queryWrapper.like("file_name", ocr.getFileName());
            }
        }
        queryWrapper.orderByDesc("created_at"); // 设置排序方式（根据创建时间倒序

        page = ocrDao.selectPage(page, queryWrapper); // 按分页查询

        myPage.setTotalRecords(page.getTotal()); // 设置返回总记录数

        return new ResponsePagingData(myPage, page.getRecords());
    }

    @Override
    public Ocr select(Long id) {
        return ocrDao.selectById(id);
    }

    @Async
    @Override
    public Object add(Ocr ocr) {
        try {
            String text = new OcrTools().getTextBySikuliOcr(ocr.getServerFileName());
            ocr.setText(text);
        } catch (Exception e) {
            ocr.setStatus(Status.FAILED);
            ocr.setText(e.getMessage());
        } catch (Error e) {
            ocr.setStatus(Status.FAILED);
            ocr.setText(e.getMessage());
        }
        return ocrDao.insert(ocr);
    }

    @Override
    public int delete(Long id) {
        return ocrDao.deleteById(id);
    }

}
